﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.IO;

namespace VCommons
{
    /// <summary>
    /// 文件上传类
    /// </summary>
    /// <remarks>
    /// Created By :王彦忠  
    /// Created Date：2011-9-13
    /// Modify By:
    /// Modify Date:
    /// Modify Reason:
    /// </remarks>
    public class UploadFile
    {
        /// <summary>
        /// 存放路径
        /// </summary>
        public string strSavePath { get; set; }

        /// <summary>
        /// 文件类型
        /// </summary>
        public string strFileExt { get; set; }

        /// <summary>
        /// 文件大小
        /// </summary>
        public int iFileLength { set; get; }

        public HttpPostedFile fileUpload { set; get; }

        #region 文件上传
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <remarks>
        /// Created By :王彦忠  
        /// Created Date：2011-9-14
        /// Modify By:
        /// Modify Date:
        /// Modify Reason:
        /// </remarks>
        /// <param name="file">文件</param>
        /// <param name="strPathAndName">文件存放路径和保存后的文件名</param>
        /// <param name="bUploadType">是否启用断点续传</param>
        /// <param name="strFileType">允许上传的文件类型 必须用分号分隔 例如.jpg;.gif</param>
        /// <param name="iFileLength">允许上传的最大文件 单位：字节</param>
        /// <param name="strInfo">返回的提示信息</param>
        /// <returns>True:上传成功 Flase:上传失败</returns>
        public bool Upload(HttpPostedFile file, string strPathAndName, bool bUploadType, string strFileType, int iFileLength, ref string strInfo)
        {
            bool bFlag = true; //返回类型 
            this.strFileExt = strFileType;
            this.iFileLength = iFileLength;

            string strExt = file.FileName.Substring(file.FileName.LastIndexOf('.')); //文件扩展名
            iFileLength = file.ContentLength;

            //检测文件类型
            if (!CheckFileType(strExt))
            {
                bFlag = false;
                strInfo = "上传文件类型错误！建议上传文件类型为" + strFileType;
            }
            //检测文件大小

            if (file.ContentLength > iFileLength)
            {
                bFlag = false;
                strInfo = "上传文件大小已经超出规定大小！建议上传文件大小为" + iFileLength / 1024 / 1024 + "M";
            }

            //检测存放目录
            string strFileName = string.Empty;
            string strFolder = string.Empty;
            CreateFolderAndGetFileName(strPathAndName, strExt, ref strFolder, ref strFileName);
            //开始存放文件
            try
            {
                if (!bUploadType)
                {
                    file.SaveAs(strFolder.Trim('\\') + @"\" + strFileName);
                }
                else
                {
                    var provider = (IServiceProvider)HttpContext.Current;
                    var workerRequest = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
                    var encoding = HttpContext.Current.Request.ContentEncoding;
                    var processor = new UploadProcessor(workerRequest);
                    processor.StreamToDisk(HttpContext.Current, encoding, strFolder);
                }
                strInfo = strPathAndName;
            }
            catch (Exception ex)
            {
                bFlag = false;
                strInfo = ex.Message;
            }
            return bFlag;
        }
        
        #endregion

        #region 检测文件类型是否正确
        /// <summary>
        /// 检测文件类型是否正确
        /// </summary>
        /// <remarks>
        /// Created By :王彦忠  
        /// Created Date：2011-9-13
        /// Modify By:
        /// Modify Date:
        /// Modify Reason:
        /// </remarks>
        /// <param name="strExt">文件类型</param>
        /// <returns>True:满足条件 False:不符合条件</returns>
        public bool CheckFileType(string strExt)
        {
            foreach (string str in strFileExt.Trim(';').Split(';'))
            {
                if (str.Equals(strExt, StringComparison.CurrentCultureIgnoreCase))
                {
                    return true;
                }
            }
            return false;
        } 
        #endregion

        #region 创建文件夹和获取保存文件的名字
        /// <summary>
        /// 创建文件夹和获取保存文件的名字
        /// </summary>
        /// <remarks>
        /// Created By :王彦忠  
        /// Created Date：2011-9-14
        /// Modify By:
        /// Modify Date:
        /// Modify Reason:
        /// </remarks>
        /// <param name="strPath">文件路径</param>
        /// <param name="strExt">文件扩展名</param>
        /// <param name="strFolder">文件夹路径</param>
        /// <param name="strFileName">文件名字</param>
        /// <returns>返回文件名</returns>
        public void CreateFolderAndGetFileName(string strPath, string strExt, ref string strFolder,ref string strFileName)
        {
            strPath = strPath.Trim('/');
            if (strPath.IndexOf('.') > 0)
            {
                strFileName = strPath.Substring(strPath.LastIndexOf('/'));
                strFolder = strPath.Substring(0, strPath.LastIndexOf('/') - 1);
            }
            else
            {
                strFileName = Guid.NewGuid() + strExt;
                strFolder = "/" + strPath + "/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
            }
            strPath = "/" + strFolder + "/" + strFileName;
            strFolder=HttpContext.Current.Server.MapPath(strFolder);
            if (!Directory.Exists(strFolder))
            {
                Directory.CreateDirectory(strFolder);
            }
           
        } 
        #endregion
    }
}
